/**
 * @description SKU控制器
 * @author 韩
 */

const { randomUUID } = require("crypto")

const model = require("../../../model/link/product_skus_link")
const { getFilter } = require("../../../utils/setFilter")
// 创建一个内容(sku和产品之间的关联)
const controller_save = async ({
    productId = undefined,
    skus = [],
    /**
     * 示例：
     * [{ id:1,productId:pd1,skus:"颜色：红色,尺码：S",price:12,stock:1230}]
     */
}) => {
    try {

        // 先清除productId这个产品所有sku信息，然后重新写入
        const deleteResult = await model.deleteMany({
            productId: { $in: productId }
        })
        if (deleteResult) {
            const document = skus.map(item => {
                return {
                    productId: item.productId,
                    sku: item.sku,
                    price: item.price,
                    stock: item.stock
                }
            })
            const result = await model.insertMany(document, { new: true });
            if (result) {
                return {
                    status: "0000",
                    message: "操作成功"
                }
            }
        } else {
            return {
                status: "0000",
                message: "SKU保存失败"
            }
        }
    } catch (error) {
        console.log("sku controller error", error)
    }
}

// 查询列表 
const controller_find = async ({ productId = null, status = undefined }) => {
    let filter = {
        status: status && { $in: status },
        productId: productId && { $in: productId }
    }
    filter = getFilter(filter)
    const list = await model.find(filter).sort({ sort: 1 })
    return list;
}


/**@description 根据id查详情 */
const controller_get = async ({ id }) => {
    const res = await model.findOne({
        id
    })
    if (res) {
        const { id, productId, skus, price, stock, sort, status } = res;
        return {
            code: 0,
            message: "查询成功",
            data: {
                id, productId, skus, price, stock, sort, status
            }
        }
    } else {
        return {
            status: '01',
            message: "未找到对应菜单数据"
        }
    }
}

// 删除
const controller_delete = async ({ ids = [] }) => {
    const deleteResult = await model.deleteMany({
        id: { $in: ids }
    });

    if (deleteResult.deletedCount) {
        return {
            status: '0000',
            message: `删除了${deleteResult.deletedCount}条数据`
        }
    } else {
        return {
            status: '0010',
            message: `删除失败`
        }
    }

}
module.exports = {
    controller_save,
    controller_find,
    controller_get,
    controller_delete,
}